#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智能餐饮供应链管理系统
主程序入口
"""

import tkinter as tk
from tkinter import ttk, messagebox
import sys
import os
import math

# 添加当前目录到路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from modules.procurement_manager import ProcurementManager
from modules.inventory_manager import InventoryManager
from modules.delivery_manager import DeliveryManager
from modules.data_manager import DataManager

class SupplyChainManagementSystem:
    def __init__(self):
        self.root = tk.Tk()
        self.root.title("智能餐饮供应链管理系统")
        self.root.geometry("1200x800")
        self.root.configure(bg='#f0f0f0')
        
        # 初始化数据管理器
        self.data_manager = DataManager()
        
        # 初始化各个模块
        self.procurement_manager = ProcurementManager(self.data_manager)
        self.inventory_manager = InventoryManager(self.data_manager)
        self.delivery_manager = DeliveryManager(self.data_manager)
        
        self.setup_ui()
        
    def setup_ui(self):
        """设置用户界面"""
        # 创建主标题
        title_frame = tk.Frame(self.root, bg='#2c3e50', height=80)
        title_frame.pack(fill='x', padx=10, pady=5)
        title_frame.pack_propagate(False)
        
        title_label = tk.Label(title_frame, text="智能餐饮供应链管理系统", 
                              font=('微软雅黑', 24, 'bold'), 
                              fg='white', bg='#2c3e50')
        title_label.pack(expand=True)
        
        # 创建主菜单框架
        menu_frame = tk.Frame(self.root, bg='#ecf0f1', height=60)
        menu_frame.pack(fill='x', padx=10, pady=5)
        menu_frame.pack_propagate(False)
        
        # 菜单按钮
        buttons = [
            ("采购管理", self.show_procurement),
            ("库存管理", self.show_inventory),
            ("配送管理", self.show_delivery),
            ("数据分析", self.show_analytics),
            ("系统设置", self.show_settings)
        ]
        
        for i, (text, command) in enumerate(buttons):
            btn = tk.Button(menu_frame, text=text, command=command,
                           font=('微软雅黑', 12), width=12, height=2,
                           bg='#3498db', fg='white', relief='flat',
                           activebackground='#2980b9', activeforeground='white')
            btn.pack(side='left', padx=10, pady=10)
        
        # 创建主内容区域
        self.content_frame = tk.Frame(self.root, bg='white')
        self.content_frame.pack(fill='both', expand=True, padx=10, pady=5)
        
        # 显示欢迎界面
        self.show_welcome()
        
    def clear_content(self):
        """清空内容区域"""
        for widget in self.content_frame.winfo_children():
            widget.destroy()
            
    def show_welcome(self):
        """显示欢迎界面"""
        self.clear_content()
        
        welcome_frame = tk.Frame(self.content_frame, bg='white')
        welcome_frame.pack(expand=True, fill='both')
        
        # 欢迎信息
        welcome_label = tk.Label(welcome_frame, 
                                text="欢迎使用智能餐饮供应链管理系统",
                                font=('微软雅黑', 20, 'bold'),
                                bg='white', fg='#2c3e50')
        welcome_label.pack(pady=50)
        
        # 系统功能介绍
        features_text = """
        系统主要功能：
        
        📦 采购管理 - 管理食材采购订单，记录采购数量、价格、供应商信息
        📊 库存管理 - 实时监控库存状态，智能预警库存不足
        🚚 配送管理 - 优化配送路径，降低配送成本
        📈 数据分析 - 分析采购和配送数据，优化供应链效率
        ⚙️ 系统设置 - 配置系统参数和基础数据
        """
        
        features_label = tk.Label(welcome_frame, text=features_text,
                                 font=('微软雅黑', 12),
                                 bg='white', fg='#34495e',
                                 justify='left')
        features_label.pack(pady=20)
        
    def show_procurement(self):
        """显示采购管理界面"""
        self.clear_content()
        self.procurement_manager.create_ui(self.content_frame)
        
    def show_inventory(self):
        """显示库存管理界面"""
        self.clear_content()
        self.inventory_manager.create_ui(self.content_frame)
        
    def show_delivery(self):
        """显示配送管理界面"""
        self.clear_content()
        self.delivery_manager.create_ui(self.content_frame)
        
    def show_analytics(self):
        """显示数据分析界面"""
        self.clear_content()
        
        analytics_frame = tk.Frame(self.content_frame, bg='white')
        analytics_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        title_label = tk.Label(analytics_frame, text="数据分析", 
                              font=('微软雅黑', 16, 'bold'),
                              bg='white', fg='#2c3e50')
        title_label.pack(pady=10)
        
        # 创建上下分割的布局
        top_frame = tk.Frame(analytics_frame, bg='white')
        top_frame.pack(fill='x', pady=10)
        
        bottom_frame = tk.Frame(analytics_frame, bg='white')
        bottom_frame.pack(fill='both', expand=True, pady=10)
        
        # 上半部分：统计概览
        stats_frame = tk.LabelFrame(top_frame, text="统计概览", 
                                   font=('微软雅黑', 12, 'bold'),
                                   bg='white', fg='#2c3e50')
        stats_frame.pack(fill='x', pady=5)
        
        # 获取统计数据
        procurement_orders = self.data_manager.get_procurement_orders()
        inventory_items = self.data_manager.get_inventory_items()
        delivery_orders = self.data_manager.get_delivery_orders()
        
        # 计算统计指标
        total_procurement_amount = sum(order.get('total_amount', 0) for order in procurement_orders)
        total_inventory_value = sum(item.get('current_stock', 0) * item.get('unit_price', 0) for item in inventory_items)
        total_delivery_amount = sum(order.get('total_amount', 0) for order in delivery_orders)
        total_delivery_cost = sum(order.get('delivery_cost', 0) for order in delivery_orders)
        
        # 统计信息网格布局
        stats_grid = tk.Frame(stats_frame, bg='white')
        stats_grid.pack(fill='x', padx=20, pady=10)
        
        # 创建统计卡片
        self._create_stat_card(stats_grid, "采购订单", len(procurement_orders), f"¥{total_procurement_amount:,.2f}", "#3498db", 0, 0)
        self._create_stat_card(stats_grid, "库存商品", len(inventory_items), f"¥{total_inventory_value:,.2f}", "#27ae60", 0, 1)
        self._create_stat_card(stats_grid, "配送订单", len(delivery_orders), f"¥{total_delivery_amount:,.2f}", "#e74c3c", 0, 2)
        self._create_stat_card(stats_grid, "配送成本", f"¥{total_delivery_cost:,.2f}", f"{len([o for o in delivery_orders if o.get('status') == '已完成'])}单完成", "#f39c12", 0, 3)
        
        # 下半部分：图表区域
        chart_frame = tk.Frame(bottom_frame, bg='white')
        chart_frame.pack(fill='both', expand=True)
        
        # 左侧图表
        left_chart_frame = tk.LabelFrame(chart_frame, text="库存分类分布", 
                                        font=('微软雅黑', 11, 'bold'),
                                        bg='white', fg='#2c3e50')
        left_chart_frame.pack(side='left', fill='both', expand=True, padx=(0, 10))
        
        # 绘制库存分类饼图
        self._draw_inventory_pie_chart(left_chart_frame, inventory_items)
        
        # 右侧图表
        right_chart_frame = tk.LabelFrame(chart_frame, text="订单状态统计", 
                                         font=('微软雅黑', 11, 'bold'),
                                         bg='white', fg='#2c3e50')
        right_chart_frame.pack(side='right', fill='both', expand=True, padx=(10, 0))
        
        # 绘制订单状态柱状图
        self._draw_order_status_chart(right_chart_frame, procurement_orders, delivery_orders)
        
    def _create_stat_card(self, parent, title, value, subtitle, color, row, col):
        """创建统计卡片"""
        card_frame = tk.Frame(parent, bg=color, relief='raised', bd=2)
        card_frame.grid(row=row, column=col, padx=10, pady=5, sticky='ew')
        
        # 配置列权重
        parent.grid_columnconfigure(col, weight=1)
        
        # 标题
        title_label = tk.Label(card_frame, text=title, 
                              font=('微软雅黑', 10, 'bold'),
                              bg=color, fg='white')
        title_label.pack(pady=(10, 5))
        
        # 主要数值
        value_label = tk.Label(card_frame, text=str(value), 
                              font=('微软雅黑', 14, 'bold'),
                              bg=color, fg='white')
        value_label.pack(pady=2)
        
        # 副标题
        subtitle_label = tk.Label(card_frame, text=subtitle, 
                                 font=('微软雅黑', 8),
                                 bg=color, fg='white')
        subtitle_label.pack(pady=(2, 10))
        
    def _draw_inventory_pie_chart(self, parent, inventory_items):
        """绘制库存分类饼图"""
        canvas = tk.Canvas(parent, bg='white', height=250)
        canvas.pack(fill='both', expand=True, padx=10, pady=10)
        
        if not inventory_items:
            canvas.create_text(150, 125, text="暂无库存数据", 
                              font=('微软雅黑', 12), fill='gray')
            return
        
        # 统计各分类的数量和价值
        category_stats = {}
        for item in inventory_items:
            category = item.get('category', '未分类')
            if category not in category_stats:
                category_stats[category] = {'count': 0, 'value': 0}
            category_stats[category]['count'] += 1
            category_stats[category]['value'] += item.get('current_stock', 0) * item.get('unit_price', 0)
        
        # 颜色配置
        colors = ['#3498db', '#e74c3c', '#2ecc71', '#f39c12', '#9b59b6', '#1abc9c']
        
        # 计算总价值
        total_value = sum(stats['value'] for stats in category_stats.values())
        
        if total_value == 0:
            canvas.create_text(150, 125, text="暂无有效数据", 
                              font=('微软雅黑', 12), fill='gray')
            return
        
        # 绘制饼图
        center_x, center_y = 120, 120
        radius = 80
        start_angle = 0
        
        legend_x = 250
        legend_y = 50
        
        for i, (category, stats) in enumerate(category_stats.items()):
            # 计算角度
            angle = (stats['value'] / total_value) * 360
            color = colors[i % len(colors)]
            
            # 绘制扇形
            canvas.create_arc(center_x - radius, center_y - radius,
                             center_x + radius, center_y + radius,
                             start=start_angle, extent=angle,
                             fill=color, outline='white', width=2)
            
            # 绘制标签
            label_angle = start_angle + angle / 2
            label_x = center_x + (radius + 30) * math.cos(math.radians(label_angle))
            label_y = center_y + (radius + 30) * math.sin(math.radians(label_angle))
            
            percentage = (stats['value'] / total_value) * 100
            canvas.create_text(label_x, label_y, 
                              text=f"{percentage:.1f}%",
                              font=('微软雅黑', 8, 'bold'), 
                              fill=color)
            
            # 绘制图例
            canvas.create_rectangle(legend_x, legend_y + i * 25, 
                                   legend_x + 15, legend_y + i * 25 + 15,
                                   fill=color, outline='white')
            canvas.create_text(legend_x + 20, legend_y + i * 25 + 7, 
                              text=f"{category} ({stats['count']}种)",
                              font=('微软雅黑', 9), fill='#2c3e50', anchor='w')
            
            start_angle += angle
            
    def _draw_order_status_chart(self, parent, procurement_orders, delivery_orders):
        """绘制订单状态柱状图"""
        canvas = tk.Canvas(parent, bg='white', height=250)
        canvas.pack(fill='both', expand=True, padx=10, pady=10)
        
        # 统计采购订单状态
        procurement_status = {}
        for order in procurement_orders:
            status = order.get('status', '未知')
            procurement_status[status] = procurement_status.get(status, 0) + 1
        
        # 统计配送订单状态
        delivery_status = {}
        for order in delivery_orders:
            status = order.get('status', '未知')
            delivery_status[status] = delivery_status.get(status, 0) + 1
        
        # 获取所有状态
        all_statuses = set(list(procurement_status.keys()) + list(delivery_status.keys()))
        
        if not all_statuses:
            canvas.create_text(150, 125, text="暂无订单数据", 
                              font=('微软雅黑', 12), fill='gray')
            return
        
        # 绘制柱状图
        chart_width = 300
        chart_height = 180
        chart_x = 50
        chart_y = 40
        
        # 计算最大值用于缩放
        max_value = max(
            max(procurement_status.values()) if procurement_status else 0,
            max(delivery_status.values()) if delivery_status else 0
        )
        
        if max_value == 0:
            canvas.create_text(150, 125, text="暂无有效数据", 
                              font=('微软雅黑', 12), fill='gray')
            return
        
        # 绘制坐标轴
        canvas.create_line(chart_x, chart_y + chart_height, 
                          chart_x + chart_width, chart_y + chart_height,
                          fill='#2c3e50', width=2)  # X轴
        canvas.create_line(chart_x, chart_y, 
                          chart_x, chart_y + chart_height,
                          fill='#2c3e50', width=2)  # Y轴
        
        # 绘制Y轴刻度
        for i in range(0, max_value + 1, max(1, max_value // 5)):
            y = chart_y + chart_height - (i / max_value) * chart_height
            canvas.create_line(chart_x - 5, y, chart_x, y, fill='#2c3e50')
            canvas.create_text(chart_x - 10, y, text=str(i), 
                              font=('微软雅黑', 8), fill='#2c3e50', anchor='e')
        
        # 绘制柱状图
        bar_width = chart_width / (len(all_statuses) * 2 + 1)
        colors = {'采购': '#3498db', '配送': '#e74c3c'}
        
        for i, status in enumerate(all_statuses):
            x = chart_x + (i * 2 + 1) * bar_width
            
            # 采购订单柱子
            procurement_count = procurement_status.get(status, 0)
            if procurement_count > 0:
                height = (procurement_count / max_value) * chart_height
                canvas.create_rectangle(x, chart_y + chart_height - height,
                                       x + bar_width * 0.8, chart_y + chart_height,
                                       fill=colors['采购'], outline='white')
                canvas.create_text(x + bar_width * 0.4, chart_y + chart_height - height - 10,
                                  text=str(procurement_count), 
                                  font=('微软雅黑', 8), fill=colors['采购'])
            
            # 配送订单柱子
            delivery_count = delivery_status.get(status, 0)
            if delivery_count > 0:
                height = (delivery_count / max_value) * chart_height
                canvas.create_rectangle(x + bar_width * 0.8, chart_y + chart_height - height,
                                       x + bar_width * 1.6, chart_y + chart_height,
                                       fill=colors['配送'], outline='white')
                canvas.create_text(x + bar_width * 1.2, chart_y + chart_height - height - 10,
                                  text=str(delivery_count), 
                                  font=('微软雅黑', 8), fill=colors['配送'])
            
            # X轴标签
            canvas.create_text(x + bar_width * 0.8, chart_y + chart_height + 15,
                              text=status, font=('微软雅黑', 8), fill='#2c3e50')
        
        # 绘制图例
        legend_y = chart_y + chart_height + 35
        canvas.create_rectangle(chart_x, legend_y, chart_x + 15, legend_y + 10,
                               fill=colors['采购'], outline='white')
        canvas.create_text(chart_x + 20, legend_y + 5, text="采购订单",
                          font=('微软雅黑', 9), fill='#2c3e50', anchor='w')
        
        canvas.create_rectangle(chart_x + 80, legend_y, chart_x + 95, legend_y + 10,
                               fill=colors['配送'], outline='white')
        canvas.create_text(chart_x + 100, legend_y + 5, text="配送订单",
                          font=('微软雅黑', 9), fill='#2c3e50', anchor='w')
        
    def show_settings(self):
        """显示系统设置界面"""
        self.clear_content()
        
        settings_frame = tk.Frame(self.content_frame, bg='white')
        settings_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        title_label = tk.Label(settings_frame, text="系统设置", 
                              font=('微软雅黑', 16, 'bold'),
                              bg='white', fg='#2c3e50')
        title_label.pack(pady=10)
        
        # 数据管理
        data_frame = tk.LabelFrame(settings_frame, text="数据管理", 
                                  font=('微软雅黑', 12),
                                  bg='white', fg='#2c3e50')
        data_frame.pack(fill='x', pady=10)
        
        btn_frame = tk.Frame(data_frame, bg='white')
        btn_frame.pack(pady=10)
        
        tk.Button(btn_frame, text="清空所有数据", 
                 command=self.clear_all_data,
                 font=('微软雅黑', 10),
                 bg='#e74c3c', fg='white',
                 width=15).pack(side='left', padx=10)
        
        tk.Button(btn_frame, text="初始化示例数据", 
                 command=self.init_sample_data,
                 font=('微软雅黑', 10),
                 bg='#27ae60', fg='white',
                 width=15).pack(side='left', padx=10)
        
    def clear_all_data(self):
        """清空所有数据"""
        if messagebox.askyesno("确认", "确定要清空所有数据吗？此操作不可恢复！"):
            self.data_manager.clear_all_data()
            messagebox.showinfo("成功", "所有数据已清空")
            
    def init_sample_data(self):
        """初始化示例数据"""
        if messagebox.askyesno("确认", "确定要初始化示例数据吗？这将覆盖现有数据！"):
            self.data_manager.init_sample_data()
            messagebox.showinfo("成功", "示例数据已初始化")
        
    def run(self):
        """运行系统"""
        self.root.mainloop()

if __name__ == "__main__":
    app = SupplyChainManagementSystem()
    app.run() 